package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.mapper.ServeProviderMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {
    @Resource
    private IAgencyCertificationService agencyCertificationService;
    @Resource
    private AgencyCertificationAuditMapper agencyCertificationAuditMapper;
    @Resource
    private AgencyCertificationMapper agencyCertificationMapper;
    @Resource
    private ServeProviderMapper serveProviderMapper;
    /**
     * 提交认证申请
     *
     * @param dto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditCertification(AgencyCertificationAuditAddReqDTO dto) {
        Long userId = UserContext.currentUserId();
        // 判断是否是第一次申请
        AgencyCertification agency = agencyCertificationMapper.selectById(userId);
        if (ObjectUtil.isNotEmpty(agency)) {
            // 若不为第一次申请，将前一次记录删除掉，再经行添加
            agencyCertificationMapper.deleteById(agency.getId());
        }

        // 将信息存入机构认证信息表中
        AgencyCertification agencyCertification = BeanUtil.toBean(dto, AgencyCertification.class);
        agencyCertification.setId(userId);
        agencyCertification.setCertificationTime(LocalDateTime.now());
        agencyCertification.setCertificationStatus(1);
        agencyCertificationService.save(agencyCertification);
        // 将信息存入机构认证审核表中
        AgencyCertificationAudit agencyCertificationAudit = BeanUtil.toBean(agencyCertification, AgencyCertificationAudit.class);
        agencyCertificationAudit.setServeProviderId(userId);
        agencyCertificationAudit.setAuditStatus(0);
        agencyCertificationAudit.setCertificationStatus(1);
        this.save(agencyCertificationAudit);
    }

    /**
     * 查询最新的驳回原因
     *
     * @return
     */
    @Override
    public RejectReasonResDTO rejectReason() {
        Long userId = UserContext.currentUserId();
        LambdaQueryWrapper<AgencyCertificationAudit> wrapper = new QueryWrapper<AgencyCertificationAudit>().lambda()
                .eq(AgencyCertificationAudit::getServeProviderId, userId);
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditMapper.selectOne(wrapper);

        if (agencyCertificationAudit == null) {
            throw new ForbiddenOperationException("未查询到该审核表信息");
        }
        String rejectReason = agencyCertificationAudit.getRejectReason();
        return new RejectReasonResDTO(rejectReason);
    }

    /**
     * 机构认证审核信息分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQuery(AgencyCertificationAuditPageQueryReqDTO dto) {
        Page<AgencyCertificationAudit> page = PageUtils.parsePageQuery(dto, AgencyCertificationAudit.class);
        LambdaQueryWrapper<AgencyCertificationAudit> wrapper = Wrappers.<AgencyCertificationAudit>lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getName()), AgencyCertificationAudit::getName, dto.getName())
                .eq(ObjectUtil.isNotEmpty(dto.getLegalPersonName()), AgencyCertificationAudit::getLegalPersonName, dto.getLegalPersonName())
                .eq(ObjectUtil.isNotEmpty(dto.getAuditStatus()), AgencyCertificationAudit::getAuditStatus, dto.getAuditStatus())
                .eq(ObjectUtil.isNotEmpty(dto.getCertificationStatus()), AgencyCertificationAudit::getCertificationStatus, dto.getCertificationStatus());
        Page<AgencyCertificationAudit> agencyCertificationAuditPage = agencyCertificationAuditMapper.selectPage(page, wrapper);
        return PageUtils.toPage(agencyCertificationAuditPage, AgencyCertificationAuditResDTO.class);
    }

    /**
     * 审核机构认证信息
     *
     * @param id
     * @param cretificationStatus
     * @param rejectReason
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditAgencyCertification(Long id, Integer cretificationStatus, String rejectReason) {
        // 从线程中获取数据
        CurrentUserInfo currentUserInfo = UserContext.currentUser();
        Long auditorId = currentUserInfo.getId();
        String auditorName = currentUserInfo.getName();
        // 查询表中对应的数据
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditMapper.selectById(id);
        if (ObjectUtil.isEmpty(agencyCertificationAudit)) {
            throw new ForbiddenOperationException("未找到对应的审核表数据");
        }
        agencyCertificationAudit.setCertificationStatus(cretificationStatus);
        agencyCertificationAudit.setAuditorId(auditorId);
        agencyCertificationAudit.setAuditorName(auditorName);
        agencyCertificationAudit.setAuditStatus(1);
        agencyCertificationAudit.setAuditTime(LocalDateTime.now());
        if (ObjectUtil.isNotEmpty(rejectReason)) {
            agencyCertificationAudit.setRejectReason(rejectReason);
        }
        // 向agency_certification表中更新数据
        agencyCertificationAuditMapper.updateById(agencyCertificationAudit);

        // 认证通过后，更新服务人员/机构表中的name字段
        if (cretificationStatus == 2) {
            LambdaUpdateWrapper<ServeProvider> wrapper = new UpdateWrapper<ServeProvider>().lambda()
                    .eq(ServeProvider::getId, agencyCertificationAudit.getServeProviderId());
            ServeProvider serveProvider = new ServeProvider();
            serveProvider.setName(agencyCertificationAudit.getName());
            serveProviderMapper.update(serveProvider, wrapper);
        }

        // 向认证信息表中更新数据
        Long serveProviderId = agencyCertificationAudit.getServeProviderId();
        LambdaUpdateWrapper<AgencyCertification> wrapper = new UpdateWrapper<AgencyCertification>().lambda()
                .eq(AgencyCertification::getId, serveProviderId);
        AgencyCertification agencyCertification = new AgencyCertification();
        agencyCertification.setCertificationStatus(cretificationStatus);
        agencyCertificationMapper.update(agencyCertification, wrapper);
    }
}